package com.neusoft.healthcity.config.scheduled;

import com.neusoft.healthcity.config.RandomNum;
import com.neusoft.healthcity.entity.ViewInfectiousDiseases;
import com.neusoft.healthcity.service.ViewInfectiousDiseasesService;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
public class XmlGeneratorInfectious {

    @Autowired
    private ViewInfectiousDiseasesService infectiousDiseasesService;

    private Logger logger = LoggerFactory.getLogger(XmlGeneratorInfectious.class);


    //区域编码
    @Value("${xmlCreate.reportZoneCode}")
    private String reportZoneCode;
    //机构编码
    @Value("${xmlCreate.reportOrgCode}")
    private String reportOrgCode;
    //授权码
    @Value("${xmlCreate.license}")
    private String license;
    //生成xml文件存放位置
    @Value("${xmlCreate.infectiousDiseases.xmlFileLocation}")
    private String XMLfilelocation;

    //生成当前时间
    String startDate = null;
    String endDate = null;

    @Scheduled(cron = "0 */10 * * * ?")
    public void xmlGeneratorInfectiousScheduled() {
        logger.info("-----------  begin -----------");
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        startDate = format.format(date);
        logger.info("--------" + startDate + "--------");
        System.out.println(infectiousDiseasesService);
        List<ViewInfectiousDiseases> scheduledInfectious = infectiousDiseasesService.getScheduledInfectious(startDate, endDate);

        //第一次的结束时间为下一次的开始时间x`
        endDate = startDate;
        logger.info("--------" + endDate + "--------");


        //根节点
        Element root = new Element("EDRDocument");

        //将根节点添加到文档中
        Document document = new Document(root);

        //文档标识ID
        String documentId=reportOrgCode+"-"
                +new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"-"
                + RandomNum.get5NumString();

        //子节点header
        Element elementHeader = new Element("Header");
        elementHeader.addContent(new Element("DocumentId").setText(documentId));
        elementHeader.addContent(new Element("OperateType").setText("Add"));
        elementHeader.addContent(new Element("BusinessActivityIdentification").setText("InfectiousDiseases"));
        elementHeader.addContent(new Element("ReportZoneCode").setText(reportZoneCode));
        elementHeader.addContent(new Element("ReportOrgCode").setText(reportOrgCode));
        elementHeader.addContent(new Element("License").setText(license));
        root.addContent(elementHeader);

        //子节点body
        Element elementBody = new Element("Body");
        root.addContent(elementBody);

        for (int i = 0; i < scheduledInfectious.size(); i++) {
            //body子节点下的子节点
            Element elementBodyPersonInfo = new Element("PersonInfo");
            //将加子节点到父节点
            elementBody.addContent(elementBodyPersonInfo);
            //定义传染病视图对象
            ViewInfectiousDiseases infectiousDiseases = scheduledInfectious.get(i);

            // 添加子节点并赋值
            //患者姓名
            elementBodyPersonInfo.addContent(new Element("PatientName").setText(infectiousDiseases.getPatientname()));
            //身份证件类别代码
            elementBodyPersonInfo.addContent(new Element("IdCardTypeCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getIdcardtypecode()).setText(infectiousDiseases.getIdcardtype()));
            //身份证件号
            elementBodyPersonInfo.addContent(new Element("IdCard").setText(infectiousDiseases.getIdcard()));
            //性别代码
            elementBodyPersonInfo.addContent(new Element("GenderCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getGendercode()).setText(infectiousDiseases.getGender()));
            //出生日期
            elementBodyPersonInfo.addContent(new Element("BirthDate").setText(infectiousDiseases.getBirthdate()));
            //国籍代码
            elementBodyPersonInfo.addContent(new Element("NationalityCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getNationalitycode()).setText(infectiousDiseases.getNationality()));
            //民族代码
            elementBodyPersonInfo.addContent(new Element("NationCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getNationcode()).setText(infectiousDiseases.getNationcode()));
            //学历代码
            elementBodyPersonInfo.addContent(new Element("EducationLevelCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getEducationlevelcode()).setText(infectiousDiseases.getEducationlevel()));
            //户籍类别代码
            elementBodyPersonInfo.addContent(new Element("DomicileAddressAttributionCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getDomicileaddressattributioncode()).setText(infectiousDiseases.getDomicileaddressattribution()));
            //户籍地址编码
            elementBodyPersonInfo.addContent(new Element("DomicileAddressCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getDomicileaddresscode()).setText(infectiousDiseases.getDomicileaddress()));
            //户籍详细地址
            elementBodyPersonInfo.addContent(new Element("DomicileAdrressDetails").setText(infectiousDiseases.getDomicileadrressdetails()));
            // 现住址类别/生前住址类别
            elementBodyPersonInfo.addContent(new Element("LivingAddressAttributionCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getLivingaddressattributioncode()).setText(infectiousDiseases.getLivingaddressattribution()));
            //现住地区编码/生前地区编码
            elementBodyPersonInfo.addContent(new Element("LivingAddressCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getLivingaddresscode()).setText(infectiousDiseases.getLivingaddress()));
            //现住详细地址/生前详细住址
            elementBodyPersonInfo.addContent(new Element("LivingAddressDetails").setText(infectiousDiseases.getLivingaddressdetails()));
            //工作单位/学校名称
            elementBodyPersonInfo.addContent(new Element("EmployerOrgName").setText(infectiousDiseases.getEmployerorgname()));
            //人群分类代码
            elementBodyPersonInfo.addContent(new Element("NultitudeTypeCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getNultitudetypecode()).setText(infectiousDiseases.getNultitudetype()));
            //人群分类代码
            elementBodyPersonInfo.addContent(new Element("OtherNultitudeType").setText(infectiousDiseases.getOthernultitudetype()));
            //婚姻状况代码
            elementBodyPersonInfo.addContent(new Element("MaritalStatusCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getMaritalstatuscode()).setText(infectiousDiseases.getMaritalstatus()));
            //联系人/监护人姓名
            elementBodyPersonInfo.addContent(new Element("Contacts").setText(infectiousDiseases.getContacts()));
            //联系人/监护人电话号码
            elementBodyPersonInfo.addContent(new Element("ContactsTel").setText(infectiousDiseases.getContactstel()));
            //联系人/监护人与本人关系代码
            elementBodyPersonInfo.addContent(new Element("ContactsRelCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getContactsrelcode()).setText(infectiousDiseases.getContactsrel()));


            //添加body节点下的DiseaseInfo节点   病例报告信息
            Element elementBodyDiseaseInfo = new Element("DiseaseInfo");
            //将DiseaseInfo节点添加到body节点
            elementBody.addContent(elementBodyDiseaseInfo);


            //添加子节点
            //数据ID
            elementBodyDiseaseInfo.addContent(new Element("Id").setText(infectiousDiseases.getId()));
            //卡片ID
            elementBodyDiseaseInfo.addContent(new Element("CardId").setText(infectiousDiseases.getCardid()));
            //卡片编号
            elementBodyDiseaseInfo.addContent(new Element("CardCode").setText(""));
            //发病日期
            elementBodyDiseaseInfo.addContent(new Element("OnsetDate").setText(infectiousDiseases.getOnsetdate()));
            //诊断时间
            elementBodyDiseaseInfo.addContent(new Element("DiagnosisDate").setText(infectiousDiseases.getDiagnosisdate()));
            //疾病诊断编码
            elementBodyDiseaseInfo.addContent(new Element("DiseaseCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getDiseasecode()).setText(infectiousDiseases.getDisease()));
            //其他具体疾病名称
            elementBodyDiseaseInfo.addContent(new Element("OtherDiseaseName").setText(infectiousDiseases.getOtherdiseasename()));
            //诊断状态代码
            elementBodyDiseaseInfo.addContent(new Element("DiagnosisTypeCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getDiagnosistypecode()).setText(infectiousDiseases.getDiagnosistype()));
            //病例分类代码
            elementBodyDiseaseInfo.addContent(new Element("CaseClassificationCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getCaseclassificationcode()).setText(infectiousDiseases.getCaseclassification()));
            //死亡日期
            elementBodyDiseaseInfo.addContent(new Element("DeathDate").setText(infectiousDiseases.getDeathdate()));

            //实验室检测结论代码
            elementBodyDiseaseInfo.addContent(new Element("LaborTestConclusionCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getLabortestconclusioncode()).setText(infectiousDiseases.getLabortestconclusion()));
            //确认（替代策略、核酸）检测阳性日期
            elementBodyDiseaseInfo.addContent(new Element("ConfirmedTestPositiveDate").setText(infectiousDiseases.getConfirmedtestpositivedate()));
            //确认（替代策略、核酸）检测单位
            elementBodyDiseaseInfo.addContent(new Element("ConfirmedTestPositiveOrgName").setText(infectiousDiseases.getConfirmedtestpositiveorgname()));
            //实验室确诊日期
            elementBodyDiseaseInfo.addContent(new Element("LaborDiagnosisDate").setText(infectiousDiseases.getLabordiagnosisdate()));
            //病人所属地类型
            elementBodyDiseaseInfo.addContent(new Element("PatientResidenceTypeCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getPatientresidencetypecode()).setText(infectiousDiseases.getPatientresidencetype()));
            //麻痹日期
            elementBodyDiseaseInfo.addContent(new Element("PalsyDate").setText(infectiousDiseases.getPalsydate()));
            //来现就诊地日期
            elementBodyDiseaseInfo.addContent(new Element("TreatmentlandDate").setText(infectiousDiseases.getTreatmentlanddate()));
            //就诊地址类型
            elementBodyDiseaseInfo.addContent(new Element("TreatmentlandTypeCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getTreatmentlandtypecode()).setText(infectiousDiseases.getTreatmentlandtype()));
            //就诊地址编码
            elementBodyDiseaseInfo.addContent(new Element("TreatmentlandZoneCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getTreatmentlandzonecode()).setText(infectiousDiseases.getTreatmentlandzone()));
            //就诊地址
            elementBodyDiseaseInfo.addContent(new Element("TreatmentlandLivingAddressDetails").setText(infectiousDiseases.getTreatlandlivadddels()));
            //麻痹症状
            elementBodyDiseaseInfo.addContent(new Element("PalsySymptom").setText(infectiousDiseases.getPalsysymptom()));
            //患者登记号
            elementBodyDiseaseInfo.addContent(new Element("PatientRegistrationNumber").setText(infectiousDiseases.getPatientregistrationnumber()));
            //性病史代码
            elementBodyDiseaseInfo.addContent(new Element("VenerealHistoryCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getVenerealhistorycode()).setText(infectiousDiseases.getVenerealhistory()));
            //发现方式（样本来源）
            elementBodyDiseaseInfo.addContent(new Element("DiscoveryModeCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getDiscoverymodecode()).setText(infectiousDiseases.getDiscoverymode()));
            //样本来源其他
            elementBodyDiseaseInfo.addContent(new Element("DiscoveryModeOther").setText(infectiousDiseases.getDiscoverymodeother()));
            //严重程度（是否重症）
            elementBodyDiseaseInfo.addContent(new Element("ServerityCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getServeritycode()).setText(infectiousDiseases.getServerity()));
            //临床严重程度
            elementBodyDiseaseInfo.addContent(new Element("ClinicalServerityCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getClinicalserveritycode()).setText(infectiousDiseases.getClinicalserverity()));
            //感染途径
            elementBodyDiseaseInfo.addContent(new Element("InfectionRouteCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getInfectionroutecode()).setText(infectiousDiseases.getInfectionroute()));
            //感染途径其他
            elementBodyDiseaseInfo.addContent(new Element("InfectionRouteOther").setText(infectiousDiseases.getInfectionrouteother()));
            //接触方式
            elementBodyDiseaseInfo.addContent(new Element("ContactTypeCodeList").addContent(
                    new Element("ContactTypeCode").setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getContacttypecodelist())
                            .setText(infectiousDiseases.getContacttype())));
            //接触方式其它
            elementBodyDiseaseInfo.addContent(new Element("ContactTypeOther").setText(infectiousDiseases.getContacttypeother()));
            //注射毒品史  与病人共用过注射器的人数
            elementBodyDiseaseInfo.addContent(new Element("InjectionTogetherNum").setText(infectiousDiseases.getInjectiontogethernum()));
            //非婚异性性接触史 与病人有非婚性行为的人数
            elementBodyDiseaseInfo.addContent(new Element("NonmaritalSexNum").setText(infectiousDiseases.getNonmaritalsexnum()));
            //男男性行为史 发生同性性行为的人数
            elementBodyDiseaseInfo.addContent(new Element("HomosexualSexNum").setText(infectiousDiseases.getHomosexualsexnum()));
            //生殖道沙眼衣原体感染
            elementBodyDiseaseInfo.addContent(new Element("ChlamydialTrachomatisCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getChlamydialtrachomatiscode()).setText(infectiousDiseases.getChlamydialtrachomatis()));
            //实验室结果
            elementBodyDiseaseInfo.addContent(new Element("LaborTestResultCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getLabortestresultcode()).setText(infectiousDiseases.getLabortestresult()));
            elementBodyDiseaseInfo.addContent(new Element("HbsagCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getHbsagcode()).setText(infectiousDiseases.getHbsag()));
            elementBodyDiseaseInfo.addContent(new Element("HbsagFirstDate").setText(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(infectiousDiseases.getHbsagfirstdate())));
            elementBodyDiseaseInfo.addContent(new Element("HbsagAsymptomatic").setText(infectiousDiseases.getHbsagasymptomatic()));
            elementBodyDiseaseInfo.addContent(new Element("HbsagAlt").setText(infectiousDiseases.getHbsagalt()));
            elementBodyDiseaseInfo.addContent(new Element("HbcigResultCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getHbcigresultcode()).setText(infectiousDiseases.getHbcigresult()));
            elementBodyDiseaseInfo.addContent(new Element("HbliverPunctureCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getHbliverpuncturecode()).setText(infectiousDiseases.getHbliverpuncture()));
            elementBodyDiseaseInfo.addContent(new Element("HbsagChangeCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getHbsagchangecode()).setText(infectiousDiseases.getHbsagchange()));
            elementBodyDiseaseInfo.addContent(new Element("CloseContactsSymptomCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getClosecontactssymptomcode()).setText(infectiousDiseases.getClosecontactssymptom()));
            elementBodyDiseaseInfo.addContent(new Element("MgmtStatusCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getMgmtstatuscode()).setText(infectiousDiseases.getMgmtstatus()));
            elementBodyDiseaseInfo.addContent(new Element("CurrmgmtOrgCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getCurrmgmtorgcode()).setText(infectiousDiseases.getCurrmgmtorg()));
            elementBodyDiseaseInfo.addContent(new Element("CardNotes").setText(infectiousDiseases.getCardnotes()));
            elementBodyDiseaseInfo.addContent(new Element("ForeignTypeCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getForeigntypecode()).setText(infectiousDiseases.getForeigntype()));
            elementBodyDiseaseInfo.addContent(new Element("PlaceCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getPlacecode()).setText(infectiousDiseases.getPlace()));
            elementBodyDiseaseInfo.addContent(new Element("PlaceOther").setText(infectiousDiseases.getPlaceother()));
            //elementBodyDiseaseInfo.addContent(new Element("InHosDate").setText(""));
            elementBodyDiseaseInfo.addContent(new Element("OutHosDate").setText(infectiousDiseases.getOuthosdate()));
            elementBodyDiseaseInfo.addContent(new Element("ReportZoneCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getReportzonecode()).setText(infectiousDiseases.getReportzone()));
            elementBodyDiseaseInfo.addContent(new Element("ReportOrgCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getReportorgcode()).setText(infectiousDiseases.getReportorg()));
            elementBodyDiseaseInfo.addContent(new Element("FillDoctorName").setText(infectiousDiseases.getFilldoctorname()));
            elementBodyDiseaseInfo.addContent(new Element("CardFillingDate").setText(infectiousDiseases.getCardfillingdate()));
            //elementBodyDiseaseInfo.addContent(new Element("AfterCardFillingDate").setText(""));
            elementBodyDiseaseInfo.addContent(new Element("DeletingTypeCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getDeletingtypecode()).setText(infectiousDiseases.getDeletingtype()));
            elementBodyDiseaseInfo.addContent(new Element("DeletingReasonDetails").setText(infectiousDiseases.getDeletingreasondetails()));


            Element elementOperateInfo = new Element("OperateInfo");
            elementOperateInfo.addContent(new Element("OperateTypeCode").setText(infectiousDiseases.getOperatetypecode()));
            elementOperateInfo.addContent(new Element("OperateZoneCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getOperatezonecode()).setText(infectiousDiseases.getOperatezone()));
            elementOperateInfo.addContent(new Element("OperateOrgCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getOperateorgcode()).setText(infectiousDiseases.getOperateorg()));
            elementOperateInfo.addContent(new Element("OperateUser").setText(infectiousDiseases.getOperateuser()));
            elementOperateInfo.addContent(new Element("OperateUserTypeCode")
                    .setAttribute("version", "1.0").setAttribute("value", infectiousDiseases.getOperateusertypecode()).setText(infectiousDiseases.getOperateusertype()));
            elementOperateInfo.addContent(new Element("OperateDate").setText(infectiousDiseases.getOperatedate()));
            elementBodyDiseaseInfo.addContent(elementOperateInfo);

            // 输出 books.xml 文件；
            // 使xml文件 缩进效果
            Format prettyFormat = Format.getPrettyFormat();
            XMLOutputter XMLOut = new XMLOutputter(prettyFormat);
            try {
                XMLOut.output(document, new FileOutputStream("E:/test" + startDate + ".xml"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            logger.info("----------- end   -----------");
        }
    }

}
